package com.ruoyi.tj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tj.utils.PyUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
public class MyTestController {

    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysUserService userService;

    public static void readExcel(String excelFilePath) {
        try (FileInputStream fileInputStream = new FileInputStream(new File(excelFilePath));
             Workbook workbook = new XSSFWorkbook(fileInputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            for (Row row : sheet) { // 迭代每一行
                for (Cell cell : row) { // 迭代每一列
                    // 根据不同数据类型，以字符串形式输出数据
                    String cellValue = "";
                    switch (cell.getCellType()) {
                        case STRING:
                            cellValue = cell.getStringCellValue();
                            break;
                        case NUMERIC:
                            cellValue = String.valueOf(cell.getNumericCellValue());
                            break;
                        case BOOLEAN:
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                            break;
                        case FORMULA:
                            cellValue = String.valueOf(cell.getCellFormula());
                            break;
                    }
                    System.out.print(cellValue + "\t");
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void importDepts(String excelFilePath) {
        try (FileInputStream fileInputStream = new FileInputStream(new File(excelFilePath));
             Workbook workbook = new XSSFWorkbook(fileInputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 读取第一个工作表
            String areaName = "";
            Long areaId = 0L;
            Integer areaSort = 0;

            String streetName = "";
            Long streetId = 0L;
            Integer streetSort = 0;

            String groupName = "";
            Long groupId = 0L;
            Integer groupSort = 0;

            String houseName = "";
            Long houseId = 0L;
            Integer houseSort = 0;



            for (int i=1; i<sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                Cell cell = row.getCell(0);
                if(cell == null) {
                    break;
                }
                if(StringUtils.isNotEmpty(cell.getStringCellValue())) {
                    if(StringUtils.isEmpty(areaName) || !areaName.equals(cell.getStringCellValue().replaceAll("\\s", ""))) {
                        areaName = cell.getStringCellValue().replaceAll("\\s", "");
                        // 插入区部门
                        SysDept dept = new SysDept();
                        dept.setStatus("0");
                        dept.setDelFlag("0");
                        dept.setPhone("");
                        dept.setEmail("");
                        dept.setOrderNum(areaSort);
                        dept.setParentId(100L);
                        dept.setCreateBy("admin");
                        dept.setDeptName(areaName);
                        deptService.insertDept(dept);
                        areaId = dept.getDeptId();
                    }
                }

                // 街道部门
                Cell cell1 = row.getCell(1);
                if(StringUtils.isNotEmpty(cell1.getStringCellValue())) {
                    if(StringUtils.isEmpty(streetName) || !streetName.equals(cell1.getStringCellValue().replaceAll("\\s", ""))) {
                        streetName = cell1.getStringCellValue().replaceAll("\\s", "");
                        // 插入街道部门
                        SysDept dept = new SysDept();
                        dept.setStatus("0");
                        dept.setDelFlag("0");
                        dept.setPhone("");
                        dept.setEmail("");
                        dept.setOrderNum(streetSort++);
                        dept.setParentId(areaId);
                        dept.setCreateBy("admin");
                        dept.setDeptName(streetName);
                        deptService.insertDept(dept);
                        streetId = dept.getDeptId();
                    }
                }

                // 社区部门
                Cell cell2 = row.getCell(2);
                if(StringUtils.isNotEmpty(cell2.getStringCellValue())) {
                    if(StringUtils.isEmpty(groupName) || !groupName.equals(cell2.getStringCellValue().replaceAll("\\s", ""))) {
                        groupName = cell2.getStringCellValue().replaceAll("\\s", "");
                        // 插入社区部门
                        SysDept dept = new SysDept();
                        dept.setStatus("0");
                        dept.setDelFlag("0");
                        dept.setPhone("");
                        dept.setEmail("");
                        dept.setOrderNum(groupSort++);
                        dept.setParentId(streetId);
                        dept.setCreateBy("admin");
                        dept.setDeptName(groupName);
                        deptService.insertDept(dept);
                        groupId = dept.getDeptId();
                    }
                }

                Cell cell3 = row.getCell(3);
                if(StringUtils.isNotEmpty(cell3.getStringCellValue())) {
                    if(StringUtils.isEmpty(houseName) || !houseName.equals(cell3.getStringCellValue().replaceAll("\\s", ""))) {
                        // 插入小区部门
                        houseName = cell3.getStringCellValue().replaceAll("\\s", "");
                        SysDept dept = new SysDept();
                        dept.setStatus("0");
                        dept.setDelFlag("0");
                        dept.setPhone("");
                        dept.setEmail("");
                        dept.setOrderNum(houseSort++);
                        dept.setParentId(groupId);
                        dept.setCreateBy("admin");
                        dept.setDeptName(houseName);
                        deptService.insertDept(dept);
                        houseId = dept.getDeptId();
                    }
                }


                System.out.println(areaName + " " + streetName + " " + groupName + " " + houseName);

            }
            /*for (Row row : sheet) { // 迭代每一行
                for (Cell cell : row) { // 迭代每一列
                    // 根据不同数据类型，以字符串形式输出数据
                    String cellValue = "";
                    switch (cell.getCellType()) {
                        case STRING:
                            cellValue = cell.getStringCellValue();
                            break;
                        case NUMERIC:
                            cellValue = String.valueOf(cell.getNumericCellValue());
                            break;
                        case BOOLEAN:
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                            break;
                        case FORMULA:
                            cellValue = String.valueOf(cell.getCellFormula());
                            break;
                    }
                    System.out.print(cellValue + "\t");
                }
                System.out.println();
            }*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/mytest/importDepts")
    @Transactional
    public AjaxResult importDepts() {
        //String filePath = "D:\\tang\\体检\\小区名称集合.xlsx";
        //importDepts(filePath);
        return AjaxResult.success();
    }

    public static final Long ROLE_CITY = 100L;
    public static final Long ROLE_AREA = 101L;
    public static final Long ROLE_STREET = 102L;
    public static final Long ROLE_GROUP = 103L;
    public static final Long ROLE_HOUSE = 104L;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @RequestMapping("/mytest/createUsers")
    @Transactional
    public AjaxResult createUsers() {
//        LambdaQueryWrapper<SysDept> queryWrapper= new LambdaQueryWrapper<>();
//        queryWrapper.select(SysDept::getDeptId, SysDept::getParentId, SysDept::getDeptName);
//        queryWrapper.eq(SysDept::getParentId, 0L);
//        SysDept rootDetp = deptService.getOne(queryWrapper, false);
//        createUsersRecursion(rootDetp, ROLE_CITY);
        return AjaxResult.success();
    }

    private void createUsersRecursion(SysDept parentDept, Long roleId) {
        // 创建用户和角色
        SysUser user = new SysUser();
        // user.setRoleId(roleId);
        user.setUserName(parentDept.getDeptName());
        String loginName = PyUtils.getAllFirstLetter(parentDept.getDeptName().toLowerCase());

        SysUser sysUser = userService.selectUserByLoginName(loginName);
        int nameFlag = 1;
        while(sysUser != null) {
            loginName = String.format("%s%02d", loginName, nameFlag);
            sysUser = userService.selectUserByLoginName(loginName);
        }

        String password = loginName + "123";
        String salt = String.valueOf(System.currentTimeMillis());
        user.setLoginName(loginName);
        user.setSalt(salt);
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), password, salt));
        user.setDeptId(parentDept.getDeptId());
        user.setDeptPath(deptService.getDeptPath(parentDept.getDeptId()));
        user.setUserType("");
        user.setEmail("");
        user.setPhonenumber("");
        user.setDelFlag("0");
        user.setCreateBy("admin");
        user.setCreateTime(new Date());
        user.setRemark("");
        sysUserMapper.insertUser(user);

        // 用户角色
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(user.getUserId());
        sysUserRole.setRoleId(roleId);
        sysUserRoleMapper.insert(sysUserRole);

        System.out.println(parentDept.getDeptName() + " " + user.getLoginName());

        // 查询下面的部门
        if(roleId < ROLE_HOUSE) {
            LambdaQueryWrapper<SysDept> queryWrapper= new LambdaQueryWrapper<>();
            queryWrapper.select(SysDept::getDeptId, SysDept::getParentId, SysDept::getDeptName);
            queryWrapper.eq(SysDept::getParentId, parentDept.getDeptId());
            List<SysDept> deptList = deptService.list(queryWrapper);
            if(deptList.size() > 0) {
                for (SysDept dept : deptList) {
                    createUsersRecursion(dept, roleId + 1);
                }
            }
        }

    }
}
